package controller;

import model.User;
import model.UserInfo;
import model.UserNameToId;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: a
 * Date: 2022-12-07
 * Time: 15:30
 */
@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || password == null || username.equals("") || password.equals("")){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入的用户名或者密码不能为空");
            return;
        }
        //字符串哈希(将用户名转化成id)
        UserNameToId userNameToId = new UserNameToId();
        int userId = userNameToId.getId(username);
        User user = UserInfo.users[userId];
        if(user == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入的用户名或者密码错误");
            return;
        }
        System.out.println(user.getUserid() + " " + user.getUsername() + " " + user.getPassword());
        if(!user.getPassword().equals(password)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入的用户名或者密码错误");
            return;
        }
        //登录成功, 构造会话
        HttpSession session = req.getSession(true);
        //将获取到的user对象存到session里面
        session.setAttribute("user", user);
        resp.sendRedirect("microblog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //验证登录状态码
        HttpSession session = req.getSession(false);
        if(session == null){
            //未登录, 直接设置状态码为403, 不需要有body
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            //未登录, 直接设置状态码为403, 不需要有body
            resp.setStatus(403);
            return;
        }
        //已登录
        resp.setStatus(200);
    }
}
